package filter;

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

import member.*;

import util.*;

public class LogonCheckFilter implements Filter {
	
	private ArrayList<String> noCheckURLs = new ArrayList<String>();

	public void destroy() {


	}

	public void doFilter(ServletRequest request, ServletResponse response,	FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest hRequest = (HttpServletRequest)request;
		HttpServletResponse hResponse = (HttpServletResponse)response;
		
		String contextPath = hRequest.getContextPath();	
		String requestURL =hRequest.getRequestURI().toString();
		
		//System.out.println("Start LogonFilter doFilter!");
		//System.out.println("context_path:"+contextPath);
		//System.out.println("request_url:"+requestURL);
		
		
		boolean needLogon = true;
		
		for( int i  = 0 ; i < noCheckURLs.size() ; i++)
		{
			String nocheckurl = contextPath + (String)noCheckURLs.get(i);
			
			//System.out.println("no_check_url:"+nocheckurl);
			
			//ex: nocheckurl = "/StrustsProject/welcome.do 
			if(requestURL.indexOf(nocheckurl) != -1)
			{
				needLogon = false;
			}
		}
		
		//Login이 필요한 주소
		if(needLogon)
		{
			//System.out.println("needLogon:"+needLogon);
			
			HttpSession session = hRequest.getSession();
			
			User user = (User)session.getAttribute("user");
			
			
			if(user!=null){
				
				if(!user.isLogon())
				{
					//System.out.println("Access Failed!!!");
					hResponse.sendRedirect(contextPath + "/member/login.do");//welcome.jsp
					return; //더이상의 실행을 중지한다.
				}
			
			} else {
				
				session.setAttribute("membercommunity", null);
				session.setAttribute("member", null);
				hResponse.sendRedirect(contextPath + "/member/login.do");//welcome.jsp
				return; //더이상의 실행을 중지한다.
			}
		}
			
		//System.out.println("End LogonFilter doFilter!");
		chain.doFilter(request, response);
		
	}

	public void init(FilterConfig filterConfig) throws ServletException {

		
		String noCheckURL = filterConfig.getInitParameter("nocheckurl"); 
		StringTokenizer st = new StringTokenizer(noCheckURL,",");

		while(st.hasMoreTokens()){
			noCheckURLs.add(st.nextToken().trim());			
		}
	}

}
